//
//  DCLoginViewController.m
//  Demo
//
//  Created by Kyle on 2022/12/29.
//

#import "DCLoginViewController.h"
#import "TTTAttributedLabel.h"
#import "DCTabbarViewController.h"

typedef enum : NSUInteger {
    DCLoinUITypePhoneNumInput,      //输入手机号
    DCLoinUITypeSmsInput            //获取验证码
    
} DCLoinUIType;
#define TotltTime 60
@interface DCLoginViewController ()<TTTAttributedLabelDelegate>

@property (nonatomic, strong) NSTimer *timer;

@property (nonatomic, assign) NSInteger timeNumber;

@property (nonatomic, assign) DCLoinUIType currnetUIType;

@property (nonatomic, strong) UIView *phoneNumView;

@property (nonatomic, strong) UILabel *phoneNumLabel;

@property (nonatomic, strong) UITextField *phoneNumTF;

@property (nonatomic, strong) UIView *codeView;

@property (nonatomic, strong) UILabel *sendeCodeLabel;

@property (nonatomic, strong) UITextField *verificationCodeTF;

@property (nonatomic, strong) UIView *spaceView;

@property (nonatomic, strong) UIButton *nextBtn;

@end

@implementation DCLoginViewController

- (NSTimer *)timer {
    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    }
    return _timer;;
}

- (void)viewDidLoad {
    [super viewDidLoad];
//    [self setTitleName:@"login"];
}

- (void)configureAlloc {
    [super configureAlloc];
    self.currnetUIType = DCLoinUITypePhoneNumInput;
    _timeNumber = TotltTime;
}

- (void)configureUI {
    [super configureUI];
    self.view.backgroundColor = [UIColor colorWithString:@"#F0FFCE"];
    UIImageView *imageView = [UIImageView new];
    imageView.image = [UIImage imageNamed:@"loginLogo"];
    [self.view addSubview:imageView];
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(127);
        make.centerX.mas_equalTo(self.view);
    }];
    
    UIView *spaceView = [UIView new];
    _spaceView = spaceView;
    spaceView.backgroundColor = [UIColor colorWithString:@"#1C221B"];
    [self.view addSubview:spaceView];
    [spaceView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(41);
        make.width.mas_equalTo(8);
        make.height.mas_equalTo(16);
        make.top.mas_equalTo(imageView.mas_bottom).mas_offset(76);
    }];
    
    UILabel *loginLabel = [UILabel new];
    loginLabel.text = @"Login";
    loginLabel.font = DCFont_PF_Semibold(22);
    loginLabel.textColor = [UIColor colorWithString:@"#1C221B"];
    [self.view addSubview:loginLabel];
    [loginLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(spaceView.mas_right).mas_offset(5);
        make.centerY.mas_equalTo(spaceView.mas_centerY);
    }];
    
    UIView *phoneNumView = [UIView new];
    _phoneNumView = phoneNumView;
    phoneNumView.backgroundColor = [UIColor colorWithString:@"#FFFFFF"];
    phoneNumView.layer.cornerRadius = 8;
    phoneNumView.layer.masksToBounds = YES;
    [self.view addSubview:phoneNumView];
    [phoneNumView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(38);
        make.right.mas_equalTo(-38);
        make.height.mas_equalTo(50);
        make.top.mas_equalTo(spaceView.mas_bottom).mas_offset(34);
    }];
    
    UILabel *areaCodeLabel = [UILabel new];
    areaCodeLabel.text = @"+234";
    areaCodeLabel.textColor = [UIColor colorWithString:@"#1C221B"];
    areaCodeLabel.font = DCFont_PF_Semibold(14);
    [phoneNumView addSubview:areaCodeLabel];
    [areaCodeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_lessThanOrEqualTo(17);
        make.centerY.mas_equalTo(phoneNumView);
        make.width.mas_equalTo(45);
    }];
    
    UITextField *phoneNumTF = [UITextField new];
    _phoneNumTF = phoneNumTF;
//    phoneNumTF.text = @"8110287458";
//    phoneNumTF.text = @"7034400621"; //已借款 审核失败
//    phoneNumTF.text = @"7034400625"; //已借款 放款中
    phoneNumTF.text = @"7034400627"; //已借款 放款成功
//    phoneNumTF.text = @"7034400623"; //已借款 放款失败
//    phoneNumTF.text = @"7034400624"; //已借款 账单逾期
//    phoneNumTF.text = @"7034400626"; //贷款结清
    phoneNumTF.borderStyle = UITextBorderStyleNone;
    phoneNumTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    phoneNumTF.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    phoneNumTF.textAlignment = NSTextAlignmentLeft;
    phoneNumTF.keyboardType = UIKeyboardTypeNumberPad;
    phoneNumTF.textColor = [UIColor colorWithString:@"#1C221B"];
    phoneNumTF.font = DCFont_PF_Semibold(14);
//    phoneNumTF.backgroundColor = [UIColor redColor];
    [phoneNumView addSubview:phoneNumTF];
    [phoneNumTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.mas_equalTo(0);
        make.left.mas_equalTo(areaCodeLabel.mas_right).mas_offset(6);
        make.right.mas_equalTo(-17);
    }];
    
    phoneNumView.hidden = YES;
    
    UILabel *phoneNumLabel = [UILabel new];
    _phoneNumLabel = phoneNumLabel;
    phoneNumLabel.text = [NSString stringWithFormat:@"+234 %@",phoneNumTF.text];
    phoneNumLabel.textColor = [UIColor colorWithString:@"#658900"];
    phoneNumLabel.font = DCFont_PF_Medium(14);
    [self.view addSubview:phoneNumLabel];
    [phoneNumLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(41);
        make.top.mas_equalTo(spaceView.mas_bottom).mas_offset(18);
    }];
    
    UIView *codeView = [UIView new];
    _codeView = codeView;
    codeView.backgroundColor = [UIColor colorWithString:@"#FFFFFF"];
    codeView.layer.cornerRadius = 8;
    codeView.layer.masksToBounds = YES;
    [self.view addSubview:codeView];
    [codeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(38);
        make.right.mas_equalTo(-38);
        make.height.mas_equalTo(50);
        make.top.mas_equalTo(spaceView.mas_bottom).mas_offset(59);
    }];
    
    UILabel *sendeCodeLabel = [UILabel new];
    _sendeCodeLabel = sendeCodeLabel;
    sendeCodeLabel.text = @"send";
    sendeCodeLabel.textColor = [UIColor colorWithString:@"#658900"];
    sendeCodeLabel.font = DCFont_PF_Semibold(14);
    sendeCodeLabel.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapSend = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sendCodel)];
    [sendeCodeLabel addGestureRecognizer:tapSend];
    [codeView addSubview:sendeCodeLabel];
    [sendeCodeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-34);
        make.centerY.mas_equalTo(codeView);
    }];
    
    UITextField *verificationCodeTF = [[UITextField alloc] init];
    _verificationCodeTF = verificationCodeTF;
    _verificationCodeTF.text = @"0000";
    verificationCodeTF.textColor = [UIColor colorWithString:@"#1C221B"];
    verificationCodeTF.font = DCFont_PF_Semibold(14);
    NSAttributedString *placeH = [[NSAttributedString alloc] initWithString:@"Verification code" attributes:@{NSForegroundColorAttributeName:[UIColor colorWithString:@"#C7C7C7"],NSFontAttributeName:DCFont_PF_Regular(12)}
    ];
    verificationCodeTF.attributedPlaceholder = placeH;
    [codeView addSubview:verificationCodeTF];
    [verificationCodeTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(26);
        make.top.bottom.mas_equalTo(0);
        make.right.lessThanOrEqualTo(sendeCodeLabel.mas_left).mas_offset(-10);
    }];
    
    _nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _nextBtn.layer.cornerRadius = 8;
    _nextBtn.layer.masksToBounds = YES;
    _nextBtn.backgroundColor = [UIColor colorWithString:@"#1C221B"];
    _nextBtn.titleLabel.font = DCFont_PF_Semibold(15);
    [_nextBtn setTitle:@"Next" forState:UIControlStateNormal];
    [_nextBtn setTitleColor:[UIColor colorWithString:@"#FFFFFF"] forState:UIControlStateNormal];
    [_nextBtn addTarget:self action:@selector(nextAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_nextBtn];
    [_nextBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(spaceView.mas_bottom).mas_offset(147);
        make.left.mas_equalTo(38);
        make.height.mas_equalTo(50);
        make.right.mas_equalTo(-38);
    }];
    
    
    TTTAttributedLabel *bottomLabel = [[TTTAttributedLabel alloc] initWithFrame:CGRectZero];
    bottomLabel.textColor = [UIColor colorWithString:@"#000000"];
    bottomLabel.numberOfLines = 0;
    bottomLabel.delegate = self;
    bottomLabel.font = DCFont_PF_Regular(12);
    bottomLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:bottomLabel];
    [bottomLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(31);
        make.right.mas_equalTo(-31);
        make.bottom.mas_equalTo(-40 - KSafeAreaInset.bottom);
    }];
    
    //此属性可以不显示下划线，点击的颜色默认为红色
    bottomLabel.linkAttributes = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithBool:NO],(NSString *)kCTUnderlineStyleAttributeName,nil];
    //此属性可以改变点击的颜色
    bottomLabel.activeLinkAttributes = [NSDictionary dictionaryWithObjectsAndKeys: [UIColor colorWithString:@"#000000"] ,(NSString *)kCTForegroundColorAttributeName,nil];
    
    
    NSString * text = @"By logging into your account, you agree to the 《Privacy Agreement》and the 《Registration Agreement》";
    //设置需要点击的文字的颜色大小
    [bottomLabel setText:text afterInheritingLabelAttributesAndConfiguringWithBlock:^NSMutableAttributedString *(NSMutableAttributedString *mutableAttributedString) {
        
        //得到需要点击的文字的位置
         NSRange selRange=[text rangeOfString:@"《Privacy Agreement》"];
         //设定可点击文字的的大小
         UIFont *selFont = DCFont_PF_Regular(12);
         CTFontRef selFontRef = CTFontCreateWithName((__bridge CFStringRef)selFont.fontName, selFont.pointSize, NULL);
         //设置可点击文本的大小
         [mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)selFontRef range:selRange];
         //设置可点击文本的颜色
         [mutableAttributedString addAttribute:(NSString*)kCTForegroundColorAttributeName value:(id)[[UIColor colorWithString:@"#000000"] CGColor] range:selRange];
         //设置可点击文本的背景颜色
         //[mutableAttributedString addAttribute:(NSString*)kCTBackgroundColorAttributeName value:(id)[[UIColor redColor] CGColor] range:selRange];
         CFRelease(selFontRef);
         
         //得到需要点击的文字的位置
         NSRange selRange1=[text rangeOfString:@"《Registration Agreement》"];
         //设定可点击文字的的大小
         UIFont *selFont1 =  DCFont_PF_Regular(12);
         CTFontRef selFontRef1 = CTFontCreateWithName((__bridge CFStringRef)selFont1.fontName, selFont1.pointSize, NULL);
         //设置可点击文本的大小
         [mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)selFontRef1 range:selRange1];
         //设置可点击文本的颜色
         [mutableAttributedString addAttribute:(NSString*)kCTForegroundColorAttributeName value:(id)[[UIColor colorWithString:@"#000000"] CGColor] range:selRange1];
         //设置可点击文本的背景颜色
         //[mutableAttributedString addAttribute:(NSString*)kCTBackgroundColorAttributeName value:(id)[[UIColor redColor] CGColor] range:selRange1];
         CFRelease(selFontRef1);
         
         return mutableAttributedString;
     }];
    //添加点击事件
    NSRange selRange=[text rangeOfString:@"《Privacy Agreement》"];
    [bottomLabel addLinkToTransitInformation:@{@"select":@"《Privacy Agreement》"} withRange:selRange];
    
    //添加点击事件
    NSRange selRange1=[text rangeOfString:@"《Registration Agreement》"];
    [bottomLabel addLinkToTransitInformation:@{@"select":@"《Registration Agreement》"} withRange:selRange1];
    
    [self setUIType:DCLoinUITypePhoneNumInput];
}
#pragma TTTAttributedLabel Delegate
//文字的点击事件
- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithTransitInformation:(NSDictionary *)components {
    NSString *select = [components objectForKey:@"select"];
    DCWebModel *webInfo;
    if ([select isEqualToString:@"《Privacy Agreement》"]) {
        webInfo  = [DCWebModel creatPrivacyAgreement];
    } else if ([select isEqualToString:@"《Registration Agreement》"]){
        webInfo = [DCWebModel creatRegisterAgreement];
    }
    DCWebViewController *webVC = [[DCWebViewController alloc] initWithModel:webInfo];
    [self.navigationController pushViewController:webVC animated:YES];
}


- (void)nextAction:(UIButton *)sender {
    if (_currnetUIType == DCLoinUITypePhoneNumInput) {
        [self setUIType:DCLoinUITypeSmsInput];
    } else {
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [DCHttpRequest DCLoginWithPhoneNum:self.phoneNumTF.text vcode:self.verificationCodeTF.text completeBlock:^(NSURLSessionDataTask * _Nonnull operation, DCResponseData * _Nonnull responseObject) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            if (responseObject.code == 200) {
                DCUserInfo *userInfo = [DCUserInfo mj_objectWithKeyValues:responseObject.data];
                [[CacheTools sharedCacheTools] setObjectForKey:userInfo key:SMARTUSERINFO];
                DCTabbarViewController *tabbarVC = [[DCTabbarViewController alloc] init];
                //                UIWindow *keyWind = [UIApplication sharedApplication].keyWindow;
                //                keyWind.rootViewController = tabbarVC;
                if (@available(iOS 13.0, *)) {
                    if (tabbarVC.modalPresentationStyle == UIModalPresentationPageSheet) {
                        tabbarVC.modalPresentationStyle = UIModalPresentationFullScreen;
                    }
                }
                [self presentViewController:tabbarVC animated:YES completion:^{
                                    
                }];
            } else {
                [DCDCToast toastText:responseObject.message];
            }
        }];
    }
}

- (void)setUIType:(DCLoinUIType)type {
    
    self.currnetUIType = type;
    
    if (type == DCLoinUITypePhoneNumInput) {
        //输入手机号
        self.phoneNumView.hidden = NO;
        self.codeView.hidden = YES;
        self.phoneNumLabel.hidden = YES;
        [self.nextBtn mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(_spaceView.mas_bottom).mas_offset(124);
        }];
    } else {
        //输入验证码
        self.phoneNumView.hidden = YES;
        self.codeView.hidden = NO;
        self.phoneNumLabel.hidden = NO;
        [self.nextBtn mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(_spaceView.mas_bottom).mas_offset(147);
        }];
    }
}

- (void)sendCodel {
    //register login
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [DCHttpRequest DCgetSmsWithPhoneNum:self.phoneNumTF.text registerType:@"login" completeBlock:^(NSURLSessionDataTask * _Nonnull operation, DCResponseData * _Nonnull responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (responseObject.code == 200) {
            [self.timer fire];
            //【SMS verification code obtained successfully】
            [DCDCToast toastText:@"【SMS verification code obtained successfully】"];
        } else {
            [DCDCToast toastText:responseObject.message];
        }
    }];

}

- (void)timerAction {
    if (_timeNumber <= 0) {
        self.timeNumber = TotltTime;
        self.sendeCodeLabel.text = @"send";
        self.sendeCodeLabel.userInteractionEnabled = YES;
        [self.timer invalidate];
        self.timer = nil;
    } else {
        self.timeNumber --;
        self.sendeCodeLabel.text = [NSString stringWithFormat:@"%ld",_timeNumber];
        self.sendeCodeLabel.userInteractionEnabled = NO;
    }
}

- (void)backAction:(UIButton *)sender {
    if (_currnetUIType == DCLoinUITypeSmsInput) {
        [self setUIType:DCLoinUITypePhoneNumInput];
    }

}
@end
